<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入帖子标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者" prop="authorName">
        <el-input
          v-model="queryParams.authorName"
          placeholder="请输入作者昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="草稿" value="0" />
          <el-option label="已发布" value="1" />
          <el-option label="已删除" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否置顶" prop="isTop">
        <el-select v-model="queryParams.isTop" placeholder="请选择是否置顶" clearable>
          <el-option label="否" value="0" />
          <el-option label="是" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['fishing:community:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fishing:community:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fishing:community:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="communityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="帖子ID" align="center" prop="id" width="80" />
      <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="图片" align="center" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.images && scope.row.images.length > 0"
            :src="scope.row.images[0].imageUrl"
            :preview-src-list="scope.row.images.map(img => img.imageUrl)"
            fit="cover"
            style="width: 60px; height: 60px; border-radius: 4px; cursor: pointer;"
            preview-teleported
            :z-index="9999"
          />
          <span v-else style="color: #999;">无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="作者" align="center" prop="authorName" width="120" />
      <el-table-column label="点赞数" align="center" prop="likeCount" width="80" />
      <el-table-column label="评论数" align="center" prop="commentCount" width="80" />
      <el-table-column label="阅读数" align="center" prop="readCount" width="80" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="置顶" align="center" prop="isTop" width="80">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isTop"
            :active-value="1"
            :inactive-value="0"
            @change="handleTopChange(scope.row)"
            v-hasPermi="['fishing:community:edit']"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['fishing:community:query']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fishing:community:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['fishing:community:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改钓友圈帖子对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="communityRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入帖子标题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入帖子内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="帖子图片">
              <image-upload 
                v-model="form.imageUrls" 
                :limit="9" 
                :file-size="5" 
                :file-type="['png', 'jpg', 'jpeg']"
                action="/file/upload/oss"
              />
              <div style="color: #999; font-size: 12px; margin-top: 5px;">
                最多上传9张图片，每张图片不超过5MB，支持png、jpg、jpeg格式
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签" prop="tags">
              <el-input v-model="form.tags" placeholder="请输入标签，多个标签用逗号分隔" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入位置信息" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="草稿" value="0" />
                <el-option label="已发布" value="1" />
                <el-option label="已删除" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否置顶" prop="isTop">
              <el-select v-model="form.isTop" placeholder="请选择是否置顶">
                <el-option label="否" :value="0" />
                <el-option label="是" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="0" placeholder="排序值" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 帖子详情对话框 -->
    <el-dialog title="帖子详情" v-model="detailOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="帖子ID">{{ detailForm.id }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ detailForm.title }}</el-descriptions-item>
        <el-descriptions-item label="作者">{{ detailForm.authorName }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="statusOptions" :value="detailForm.status"/>
        </el-descriptions-item>
        <el-descriptions-item label="点赞数">{{ detailForm.likeCount }}</el-descriptions-item>
        <el-descriptions-item label="评论数">{{ detailForm.commentCount }}</el-descriptions-item>
        <el-descriptions-item label="阅读数">{{ detailForm.readCount }}</el-descriptions-item>
        <el-descriptions-item label="是否置顶">{{ detailForm.isTop === 1 ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="标签">{{ detailForm.tags }}</el-descriptions-item>
        <el-descriptions-item label="位置">{{ detailForm.location }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ parseTime(detailForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="内容" :span="2">
          <div style="max-height: 200px; overflow-y: auto; white-space: pre-wrap;">{{ detailForm.content }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="帖子图片" :span="2" v-if="detailForm.images && detailForm.images.length > 0">
          <div style="display: flex; flex-wrap: wrap; gap: 10px;">
            <el-image
              v-for="(image, index) in detailForm.images"
              :key="index"
              :src="image.imageUrl"
              :preview-src-list="detailForm.images.map(img => img.imageUrl)"
              :initial-index="index"
              fit="cover"
              style="width: 100px; height: 100px; border-radius: 4px; cursor: pointer;"
              preview-teleported
              :z-index="9999"
            />
          </div>
        </el-descriptions-item>
      </el-descriptions>
      
      <!-- 评论列表 -->
      <div style="margin-top: 20px;">
        <h4>评论列表</h4>
        <el-table :data="commentList" style="width: 100%" max-height="300">
          <el-table-column prop="content" label="评论内容" :show-overflow-tooltip="true" />
          <el-table-column prop="createBy" label="评论者" width="120" />
          <el-table-column prop="likeCount" label="点赞数" width="80" />
          <el-table-column prop="createTime" label="评论时间" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button link type="danger" @click="handleDeleteComment(scope.row)" v-hasPermi="['fishing:community:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="CommunityPost">
import { listCommunityPost, getCommunityPost, delCommunityPost, addCommunityPost, updateCommunityPost, toggleTop, getPostComments, deleteComment } from "@/api/fishing/community";

const { proxy } = getCurrentInstance();
const { parseTime } = proxy;

const communityList = ref([]);
const commentList = ref([]);
const open = ref(false);
const detailOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const data = reactive({
  form: {},
  detailForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    authorName: null,
    status: null,
    isTop: null,
  },
  rules: {
    title: [
      { required: true, message: "帖子标题不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "帖子内容不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, detailForm, rules } = toRefs(data);

// 状态字典
const statusOptions = ref([
  { label: "草稿", value: "0" },
  { label: "已发布", value: "1" },
  { label: "已删除", value: "2" }
]);

/** 查询钓友圈帖子列表 */
function getList() {
  loading.value = true;
  let params = proxy.addDateRange(queryParams.value, dateRange.value);
  listCommunityPost(params).then(response => {
    let data = [];
    let totalCount = 0;
    
    // 处理不同的响应格式
    if (response.data && Array.isArray(response.data)) {
      data = response.data;
      totalCount = response.data.length;
    } else if (response.data && response.data.rows) {
      data = response.data.rows;
      totalCount = response.data.total;
    } else if (response.data && response.data.data) {
      data = response.data.data;
      totalCount = response.data.data.length;
    } else {
      data = [];
      totalCount = 0;
    }
    
    communityList.value = data;
    total.value = totalCount;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    content: null,
    tags: null,
    location: null,
    status: "1",
    isTop: 0,
    sortOrder: 0,
    imageUrls: []
  };
  proxy.resetForm("communityRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加钓友圈帖子";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const postId = row.id || ids.value[0];
  getCommunityPost(postId).then(response => {
    form.value = response.data;
    // 处理图片数据，将images转换为imageUrls供组件使用
    if (form.value.images && Array.isArray(form.value.images) && form.value.images.length > 0) {
      form.value.imageUrls = form.value.images.map(img => img.imageUrl);
    } else {
      form.value.imageUrls = [];
    }
    open.value = true;
    title.value = "修改钓友圈帖子";
  });
}

/** 详情按钮操作 */
function handleDetail(row) {
  const postId = row.id;
  getCommunityPost(postId).then(response => {
    detailForm.value = response.data;
    detailOpen.value = true;
    // 获取评论列表
    getPostComments(postId).then(commentResponse => {
      commentList.value = commentResponse.data || [];
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["communityRef"].validate(valid => {
    if (valid) {
      // 处理图片数据
      const submitData = { ...form.value };
      if (submitData.imageUrls) {
        // 确保 imageUrls 是数组
        let imageArray = [];
        if (Array.isArray(submitData.imageUrls)) {
          imageArray = submitData.imageUrls;
        } else if (typeof submitData.imageUrls === 'string' && submitData.imageUrls.trim()) {
          // 如果是字符串，按逗号分割
          imageArray = submitData.imageUrls.split(',').filter(url => url.trim());
        }
        
        if (imageArray.length > 0) {
          submitData.images = imageArray.map((url, index) => ({
            imageUrl: url.trim(),
            sortOrder: index,
            description: ''
          }));
        }
      }
      delete submitData.imageUrls;

      if (form.value.id != null) {
        updateCommunityPost(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCommunityPost(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const postIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除钓友圈帖子编号为"' + postIds + '"的数据项？').then(function() {
    return delCommunityPost(postIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 置顶状态修改 */
function handleTopChange(row) {
  let text = row.isTop === 1 ? "置顶" : "取消置顶";
  proxy.$modal.confirm('确认要"' + text + '""' + row.title + '"帖子吗？').then(function() {
    return toggleTop(row.id, row.isTop);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function() {
    row.isTop = row.isTop === 0 ? 1 : 0;
  });
}

/** 删除评论 */
function handleDeleteComment(row) {
  proxy.$modal.confirm('是否确认删除该评论？').then(function() {
    return deleteComment(row.id);
  }).then(() => {
    // 重新获取评论列表
    getPostComments(detailForm.value.id).then(response => {
      commentList.value = response.data || [];
    });
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
// 确保图片预览层级足够高，不被表格内容覆盖
:deep(.el-image-viewer__wrapper) {
  z-index: 10000 !important;
}

:deep(.el-image-viewer__mask) {
  z-index: 10000 !important;
}

:deep(.el-image-viewer__canvas) {
  z-index: 10001 !important;
}

// 表格中的图片样式优化
.el-table {
  :deep(.el-image) {
    .el-image__inner {
      transition: all 0.3s;
      &:hover {
        transform: scale(1.1);
      }
    }
  }
}

// 详情对话框中的图片样式优化
.el-dialog {
  :deep(.el-image) {
    .el-image__inner {
      transition: all 0.3s;
      &:hover {
        transform: scale(1.05);
      }
    }
  }
}

// 确保对话框不会覆盖图片预览
:deep(.el-dialog__wrapper) {
  z-index: 2000;
}

// 确保表格不会覆盖图片预览
.el-table {
  position: relative;
  z-index: 1;
}
</style>